﻿using AutoMapper;
using MediatR;
using RBAC.Domain;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.Permission;

namespace RBAC.Read.Api.Application.Handler.Permission
{
    public class GetPermissionListHandler : IRequestHandler<GetPermissionListCommand, APIPaging<PermissionDto>>
    {
        private readonly IBaseRepository<PermissionModel> permissionRepository;
        private readonly IMapper mapper;
        private readonly ILogger<GetPermissionListHandler> logger;

        public GetPermissionListHandler(IBaseRepository<PermissionModel> permissionRepository, IMapper mapper, ILogger<GetPermissionListHandler> logger)
        {
            this.permissionRepository = permissionRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 获取权限列表
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIPaging<PermissionDto>> Handle(GetPermissionListCommand request, CancellationToken cancellationToken)
        {
            APIPaging<PermissionDto> res =new APIPaging<PermissionDto>();
            var permission = permissionRepository.GetALL().Where(x => x.IsDeleted == false);
            if(request.PermissionName != null)
            {
                permission= permission.Where(x => x.PermissionName.Contains(request.PermissionName));
            }
            var data = permission.OrderByDescending(x=>x.Id).Skip((request.PageIndex-1)*request.PageSize).Take(request.PageSize);
            res.PageDatas = mapper.Map<List<PermissionDto>>(data);
            res.TotalCount = permission.Count();
            res.Code = APIEnums.Success;
            res.Msg = "获取权限列表成功";
            logger.LogInformation("获取权限列表成功");
            return Task.FromResult(res);

        }
    }
}
